package cn.cookyfly.dailyreview.client;

import cn.cookyfly.dailyreview.client.utils.UtilClient;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;

public class LoginPanel extends VerticalPanel {
	
	public LoginPanel() {
		super();
		
		FlexTable layout = new FlexTable();
		layout.setCellPadding(6);
		FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();
		cellFormatter.setColSpan(0, 0, 2);
		cellFormatter.setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		layout.setHTML(0, 0, "<h2>LOGIN</h2>");
		layout.setText(1, 0, "Login ID");
		final TextBox tbLoginId = new TextBox();
		layout.setWidget(1, 1, tbLoginId);
		layout.setHTML(2, 0, "Password");
		final PasswordTextBox tbPasswd = new PasswordTextBox();
		layout.setWidget(2, 1, tbPasswd);

		tbPasswd.addKeyPressHandler(new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getCharCode() == KeyCodes.KEY_ENTER) {
					String loginId = tbLoginId.getText();
					String passwd = tbPasswd.getText();
					if (UtilClient.isBlankString(loginId) || UtilClient.isBlankString(passwd)) {
						tbPasswd.setText(null);
						return;
					}
					RpcCaller.getCaller().login(loginId, passwd, new AsyncCallback<String>() {
						public void onFailure(Throwable caught) {
							Window.alert("RPC calling failed.");
						}
						public void onSuccess(String result) {
							tbPasswd.setText(null);
							if ("false".equals(result)) {
							} else if ("true".equals(result)) {
								// logged in successfully
								tbLoginId.setText(null);
								DailyReview.showWorkbench();
							} else {
								Window.alert("LOGIN FAILD! MSG: " + result);
							}
						}
					});
				}
			}
		});

		DecoratorPanel decPanel = new DecoratorPanel();
		decPanel.setWidget(layout);
		
		setWidth("100%");
		setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		setSpacing(20);
		add(decPanel);
	}
}
